import { ts } from 'qvog-dsl';
import {
  native,
  HomeCheckHint,
} from 'qvog-dsl';

const SEVERITY = 2;
const DOC_PATH = 'docs/sensitive-storage.md';
const DESCRIPTION = 'Storing sensitive data in localStorage or sessionStorage is prohibited due to security risks such as XSS. Avoid storing passwords, tokens, or other sensitive information on the client side.';

const sensitiveKeys = ['password', 'passwd', 'pwd', 'secret', 'token', 'apikey'];

export default native<HomeCheckHint>()()
  .match((node): node is ts.CallExpression => {
    return ts.isCallExpression(node);
  })
  .when((node: ts.CallExpression) => {
    // localStorage/sessionStorage.setItem
    if (!ts.isPropertyAccessExpression(node.expression)) { return false };

    const expr = node.expression;
    const objName = expr.expression.getText();
    const methodName = expr.name.getText();

    if ((objName === 'localStorage' || objName === 'sessionStorage') && methodName === 'setItem') {
      if (node.arguments.length < 2) { return false };

      const keyArg = node.arguments[0];
      if (ts.isStringLiteral(keyArg)) {
        const keyText = keyArg.text.toLowerCase();
        return sensitiveKeys.some(keyword => keyText.includes(keyword));
      }
    }
    return false;
  })
  .report({
    severity: SEVERITY,
    description: DESCRIPTION,
    docPath: DOC_PATH,
  });
